/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 *
 * Copyright @2008 the original author or authors.
 */
package com.bluestone.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.URI;
import org.parosproxy.paros.core.proxy.ProxyListener;
import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpMessage;

import com.bluestone.BaseAction;
import com.bluestone.assertor.IAssertor;
import com.bluestone.context.IContext;
import com.bluestone.extension.paros.ProxyServer;
import com.bluestone.extension.totalvalidator.Section508Validation;
import com.bluestone.scripts.ActionScript;
import com.bluestone.scripts.Function;
import com.bluestone.util.Util;

/**
 * CallFuntionAction can execute a function.
 * @author <a href="mailto:bluesotne.master@gmail.com">daniel.q</a>
 */
public class Section508Action extends BaseAction implements ProxyListener{

	public Section508Action(ActionScript action){
		super(action);
	}

	/**
	 * This action can execute a query.
	 * @return false 
	 */

	public boolean execute(IContext context){
		
		boolean result = false;
        try{
        	ProxyServer.getProxyServer().addListener(this);
        	result = true;
        	
        }catch(Exception me){
        	me.printStackTrace();
        	Util.getLogger().error(me);        	
        }
		return result;		
	}

	public void onHttpRequestSend(HttpMessage msg) {
		// TODO Auto-generated method stub
		
	}

	public void onHttpResponseReceive(HttpMessage msg) {

		if(msg==null){
			return;
		}
		String cond = action.getPara("cond");
		if(cond!=null && cond.length()>0){
			String [] filters = cond.split(",");
			String requestUrl = msg.getRequestHeader().getURI().toString();
			Pattern p = null;
			boolean isMatch = false;
			for(int i=0; i < filters.length; i++){
				p = Pattern.compile(filters[i], Pattern.CASE_INSENSITIVE);
				if(p.matcher(requestUrl).find()){
					isMatch = true;
					break;
				}
			}
			if(!isMatch){
				return;
			}
		}
		String contentType = msg.getResponseHeader().getHeader(HttpHeader.CONTENT_TYPE).toLowerCase();
		if((contentType.indexOf("text/html")>-1 || contentType.indexOf("text/plain")>-1)){
			byte [] bytes = msg.getResponseBody().getBytes();
			if(bytes.length<=0){
				return;
			}
			try{
				URI uri = msg.getRequestHeader().getURI();
				String target = action.getPara("target");
				if(target==null){
					target= ".\\section508\\pages\\";
				}
				target = target + uri.getHost()+uri.getPath();
				File file = new File(target.trim());
				String path = file.getParent()+"\\page"+System.currentTimeMillis()+".html";
				File file1 = new File(path);
				boolean flag = mkdirs(file.getParent());
				if(flag){
					java.io.FileOutputStream out = new java.io.FileOutputStream(file1);					
					out.write(msg.getResponseBody().getBytes());
					out.flush();
					out.close();
					Section508Validation.getSection508Validation().validate(path);
				}else{
					System.out.println("create dirs failure!");
				}			
			}catch(Exception me){
				me.printStackTrace();
			}
		}		
	}
	
	synchronized private boolean mkdirs(String path){
		boolean flag = true;
		File file = new File(path);
		if(!file.exists()){
			flag = file.mkdirs();
		}
		return flag;
	}
	




}


